﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace GtsServer.Common
{
    public class CookieHelper
    {
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="paras">参数集合</param>
        /// <param name="cookieName">cookie名称</param>
        public static void SetCookie(Dictionary<string,string> paras,string cookieName)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            foreach (var query in paras)
            {
                cookie[query.Key] = HttpContext.Current.Server.UrlEncode(query.Value);
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="cookieName">cookie名称</param>
        /// <param name="value">cookie的值</param>
        public static void SetCookie(string cookieName, string value)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Value = value;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 根据Cookiemingc获取Cookie值
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string GetCookieValue(string cookieName)
        {
            string value = string.Empty;
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                value = HttpContext.Current.Request.Cookies[cookieName].Value;
            }
            return value;
        }

        /// <summary>
        /// 根据cookie名称获取cookie键值对集合
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetCookieValues(string cookieName)
        {
            Dictionary<string, string> paras = new Dictionary<string, string>();
            if (HttpContext.Current.Request.Cookies[cookieName] != null &&HttpContext.Current.Request.Cookies[cookieName].HasKeys)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];

                for (int i = 0; i < cookie.Values.Count; i++)
                {
                    paras.Add(cookie.Values.AllKeys[i].ToString(), HttpContext.Current.Server.UrlDecode(cookie.Values[i]));
                }
            }
            return paras;
        }
    }
}
